package com.qyer.search.storm.util;

import com.qyer.search.storm.exception.DBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.sql.*;
/**
 * Created by tangzheng on 16/1/11.
 */
public class CityService {
  private static final Logger LOGGER = LoggerFactory.getLogger(CityService.class);
  private volatile static CityService singleton;
  private Map<Integer, String> cities;


  private CityService (Map<String, Object> config, String boltPrefix){
    cities = new HashMap<>();

    String DBurl = String.valueOf(config.get(boltPrefix + "db.city.url"));
    String user = String.valueOf(config.get(boltPrefix + "db.city.user"));
    String pass = String.valueOf(config.get(boltPrefix + "db.city.password"));
    String sql = "select id,cityname from city where cityname != '';";

    Connection conn = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");
      conn = java.sql.DriverManager.getConnection(DBurl, user, pass);
      Statement stmt = conn.createStatement();
      ResultSet res = stmt.executeQuery(sql);
      int id;
      String name;
      while (res.next()){
        id = res.getInt(1);
        name = res.getString(2);
        cities.put(id, name);
        //LOGGER.info("CITY_ID  :{}", id);
        //LOGGER.info("CITY_NAME:{}", name);
      }
    }catch (Exception e){
      e.printStackTrace();
      LOGGER.error("city map get failed,{}", e);
    }finally {
      try {
        if (conn != null) {
          conn.close();
        }
      }catch (Exception ee){
        LOGGER.error(ee.getMessage());
      }
    }
  }
  public static CityService getInstance(Map<String, Object> config, String boltPrefix) {
    if (singleton == null) {
      synchronized (CityService.class) {
        if (singleton == null) {
          singleton = new CityService(config, boltPrefix);
        }
      }
    }
    //System.out.println(singleton.cities);

    return singleton;
  }

  public String getCityName(int id){
    return cities.get(id);
  }

}